import 'package:flutter/material.dart';
import 'package:dio/dio.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'dart:io';

import 'package:atten_sys/utils/utils.dart';
import 'package:atten_sys/utils/http.dart';

class ChangePass extends StatefulWidget {
  ChangePass({Key key}) : super(key: key);

  @override
  State<StatefulWidget> createState() {
    // TODO: implement createState
    return _ChangePassState();
  }
}

class _ChangePassState extends State<ChangePass> {
  bool _isObscure1, _isObscure2;
  Color _eyeColor1, _eyeColor2;

  String _oldPass, _newPass;

  HttpUtil _http = HttpUtil.getInstance();

  final _formKey = GlobalKey<FormState>();

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    _isObscure1 = true;
    _isObscure2 = true;

    _eyeColor1 = Colors.grey;
    _eyeColor2 = Colors.grey;
  }

  @override
  Widget build(BuildContext context) {
    // TODO: implement build
    return Form(
        key: _formKey,
        child: ListView(
      padding: EdgeInsets.symmetric(horizontal: 20),
      children: <Widget>[
        SizedBox(
          height: 100,
        ),
        buildOldTextField(),
        SizedBox(
          height: 50,
        ),
        buildNewTextField(),
        SizedBox(
          height: 50,
        ),
        SizedBox(
          height: 50,
        ),
        RaisedButton(
          onPressed: () {
            if (_formKey.currentState.validate()) {
              //验证成功则保存数据
              _formKey.currentState.save();
              submit();
            }
          },
          color: Colors.blue,
          highlightColor: Colors.blue[700],
          colorBrightness: Brightness.dark,
          splashColor: Colors.grey,
          shape:
              RoundedRectangleBorder(borderRadius: BorderRadius.circular(20)),
          child: Text(
            '修改',
            style: TextStyle(fontSize: 20, fontWeight: FontWeight.w500),
          ),
        )
      ],
    ));
  }

  //发送网络请求
  submit() async {
    SharedPreferences preferences = await SharedPreferences.getInstance();
    dynamic data = await _http.post('/app/password',
        data: {'old': _oldPass, 'new1': _newPass},
        options: new Options(
            headers: {'Authorization': preferences.getString('Authorization')},
            contentType:
                ContentType.parse("application/x-www-form-urlencoded")));
    if (data['payload'] != null) {
      DialogUtil.createDialog(context, '提示', data['payload']);
    }
  }

  TextFormField buildOldTextField() {
    return TextFormField(
      obscureText: _isObscure1,
      decoration: InputDecoration(
          labelText: '旧密码',
          prefixIcon: Icon(Icons.lock),
          suffixIcon: IconButton(
              icon: Icon(
                Icons.remove_red_eye,
                color: _eyeColor1,
              ),
              onPressed: () {
                setState(() {
                  _isObscure1 = !_isObscure1;
                  _eyeColor1 = _isObscure1 ? Colors.grey : Colors.blue;
                });
              })),
      validator: (String value) {
        print('Enter the Password validator');
        var reg = RegExp(r'^[a-z0-9]{6,12}$');
        if (!reg.hasMatch(value)) return '请输入正确的6-12位密码';
      },
      onSaved: (String value) => _oldPass = value,
    );
  }

  TextFormField buildNewTextField() {
    return TextFormField(
      obscureText: _isObscure2,
      decoration: InputDecoration(
          labelText: '新密码',
          prefixIcon: Icon(Icons.add),
          suffixIcon: IconButton(
              icon: Icon(
                Icons.remove_red_eye,
                color: _eyeColor2,
              ),
              onPressed: () {
                setState(() {
                  _isObscure2 = !_isObscure2;
                  _eyeColor2 = _isObscure2 ? Colors.grey : Colors.blue;
                });
              })),
      validator: (String value) {
        print('Enter the Password validator');
        var reg = RegExp(r'^[a-z0-9]{6,12}$');
        if (!reg.hasMatch(value)) return '请输入6-12位密码';
        if (_oldPass == value) return '新密码不能和旧密码一致';
      },
      onSaved: (String value) => _newPass = value,
    );
  }
}
